/*
 * 验证字符串是否为空（也不能为纯空格）
 * true--说明为空， false--说明不为空
 */
export function isEmptyString(string) {
  if (
    string == undefined ||
    typeof string == 'undefined' ||
    !string ||
    string == null ||
    string == '' ||
    /^\s+$/gi.test(string)
  ) {
    return true
  } else {
    return false
  }
}

/**
 * 判断数据类型
 * @param {any} val - 基本类型数据或者引用类型数据
 * @return {string} - 可能返回的结果有，均为小写字符串
 * number、boolean、string、null、undefined、array、object、function等
 */
export function getType(val) {
  //判断数据是 null 和 undefined 的情况
  if (val == null) {
    return val + ''
  }
  return typeof val === 'object' ? Object.prototype.toString.call(val).slice(8, -1).toLowerCase() : typeof val
}

/*
 * 验证是否为数字
 */
export function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n)
}

/*
 * 是否为数组
 */
export function isArray(obj) {
  return Object.prototype.toString.call(obj) === '[object Array]'
}

/*
 * 是否空数组
 */
export function isArrayEmpty(val) {
  if (val && val instanceof Array && val.length > 0) {
    return false
  } else {
    return true
  }
}

/**
 *相差的毫秒数转换为天数
 */
export const DateDiff = (sDate1, sDate2) => {
  console.log(sDate1, sDate2, 'sDate1,  sDate2')

  var aDate, oDate1, oDate2, iDays
  aDate = sDate1.split('-')
  oDate1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]) //转换为12-18-2002格式
  aDate = sDate2.split('-')
  oDate2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0])
  iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24) //把相差的毫秒数转换为天数
  return iDays
}

/*
 * 获取url参数字符串
 * 没有返回null
 */
export function getQueryString(name) {
  let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
  let r = window.location.search.substr(1).match(reg)
  if (r != null) {
    return unescape(r[2])
  }
  return null
}

/*
 * 递归深拷贝
 */
export function deepCopy(obj) {
  let result = Array.isArray(obj) ? [] : {}
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      if (typeof obj[key] === 'object' && obj[key] !== null) {
        result[key] = deepCopy(obj[key])
      } else {
        result[key] = obj[key]
      }
    }
  }
  return result
}

/**
 * 去除参数空数据（用于向后台传递参数的时候）
 * @param {Object} obj [参数对象]
 */
export function filterEmptyData(obj) {
  for (let prop in obj) {
    obj[prop] === '' ? delete obj[prop] : obj[prop]
  }
  return obj
}

/**
 * @desc  函数防抖，用于将多次执行变为最后一次执行
 * @param {function} func - 需要使用函数防抖的被执行的函数。必传
 * @param {Number} wait - 多少毫秒之内触发，只执行第一次，默认1000ms。可以不传
 */
export function debounce(fn, delay) {
  delay = delay || 1000 //默认1s后执行
  let timer = null
  return function () {
    let context = this
    let arg = arguments
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fn.apply(context, arg)
    }, delay)
  }
}

/**
 * 节流函数, 用于将多次执行变为每隔一段时间执行
 * @param fn 事件触发的操作
 * @param delay 间隔多少毫秒需要触发一次事件
 */
export function throttle2(fn, delay) {
  let timer = null
  return function () {
    let context = this
    let args = arguments
    if (!timer) {
      timer = setTimeout(function () {
        fn.apply(context, args)
        clearTimeout(timer)
      }, delay)
    }
  }
}
/**
 * 时间格式化
 * @parmas date 时间串
 */
export function formateTime(date) {
  var y = date.getFullYear()
  var m = date.getMonth() + 1
  m = m < 10 ? '0' + m : m
  var d = date.getDate()
  d = d < 10 ? '0' + d : d
  var h = date.getHours()
  h = h < 10 ? '0' + h : h
  var minute = date.getMinutes()
  minute = minute < 10 ? '0' + minute : minute
  var second = date.getSeconds()
  second = second < 10 ? '0' + second : second
  return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second
}

export const urlParams = () => {
  const fullUrl = location.href
  const url = fullUrl.substr(fullUrl.indexOf('?')) //获取url中"?"符后的字串
  const theRequest = new Object()
  if (url.indexOf('?') != -1) {
    const str = url.substr(1)
    const strs = str.split('&')
    for (var i = 0; i < strs.length; i++) {
      theRequest[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1])
    }
  }
  return theRequest
}

/*
 * @param time 需要转化的时间戳
 * @param split 以特定符号分割
 */
export const formatTime = (time, split) => {
  let date = new Date(time - 0)
  let s = split
  if (!s) {
    s = '-'
  }
  let year = date.getFullYear(),
    month = date.getMonth() + 1, //月份是从0开始的
    day = date.getDate(),
    hour = date.getHours(),
    min = date.getMinutes(),
    sec = date.getSeconds()
  let newTime =
    year +
    s +
    (month < 10 ? '0' + month : month) +
    s +
    (day < 10 ? '0' + day : day) +
    ' ' +
    (hour < 10 ? '0' + hour : hour) +
    ':' +
    (min < 10 ? '0' + min : min) +
    ':' +
    (sec < 10 ? '0' + sec : sec)

  return newTime
}
/**
 * 检验车牌号
 * params val 车牌号
 */
// 检验车牌号
export const isCarNum = val => {
  var patrn =
    /^([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1})$/
  var patrn2 =
    /^([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))$/
  if (!patrn.test(val) && !patrn2.test(val)) {
    return false
  } else {
    return true
  }
}

/**
 * js小数乘法
 * @param val
 * @returns {number}
 *
 * accMul(0.5, 0.6) => 3, 只允许传入两个参数。%计算可以这样ride(0.5, 100) => 50。
 */
export function accMul(...val) {
  const strVal = val[0].toString()
  const strValTwo = val[1].toString()
  const index = strVal.indexOf('.')
  const indexTwo = strValTwo.indexOf('.')
  const num = [0, 0]
  if (index > -1) {
    num[0] = strVal.length - 1 - index
  }
  if (indexTwo > -1) {
    num[1] = strValTwo.length - 1 - index
  }
  return Math.round(val[0] * Math.pow(10, num[0]) * (val[1] * Math.pow(10, num[1]))) / Math.pow(10, num[0] + num[1])
}

/**
 * js小数除法
 * @param val
 * @param valTwo
 * @returns {number}
 *
 * accDiv(0.5, 0.2) => 2.5, 只允许传入两个参数。如果计算出现无穷数请后期根据需要修改最后代码进行取舍。
 */
export function accDiv(val, valTwo = 100) {
  const strVal = val.toString()
  const strValTwo = valTwo.toString()
  const index = strVal.indexOf('.')
  const indexTwo = strValTwo.indexOf('.')
  const num = [0, 0]
  if (index > -1) {
    num[0] = strVal.length - 1 - index
  }
  if (indexTwo > -1) {
    num[1] = strValTwo.length - 1 - index
  }
  return (
    Math.round(val * Math.pow(10, num[0])) / (Math.round(valTwo * Math.pow(10, num[1])) * Math.pow(10, num[0] - num[1]))
  )
}

/**
 * js 加法
 * @param val
 * @returns {number}
 *
 * add(0.1, 0.2, 0.3, 0.4) => 1。可以传多个参数进行相加。
 */
export function add(...val) {
  let max = 0
  let count = 0
  for (let i = 0; i < val.length; i++) {
    const strVal = val[i].toString()
    const index = strVal.indexOf('.')
    let num = 0
    if (index > -1) {
      num = strVal.length - 1 - index
      max = num > max ? num : max
    }
  }
  for (let i = 0; i < val.length; i++) {
    count += Math.round(val[i] * Math.pow(10, max))
  }
  return count / Math.pow(10, max)
}

/**
 * js 减法
 * @param val
 * @returns {number}
 *
 * sub(1, 0.2, 0.3, 0.4) => 0.1。相当于1 - 0.2 -0.3 -0.4；可以传多个参数，使用首位减后面的所有参数。
 */
export function sub(...val) {
  let max = 0
  let count = val[0] | 0
  for (let i = 0; i < val.length; i++) {
    const strVal = val[i].toString()
    const index = strVal.indexOf('.')
    let num = 0
    if (index > -1) {
      num = strVal.length - 1 - index
      max = num > max ? num : max
    }
  }
  for (let i = 0; i < val.length; i++) {
    count -= Math.round(val[i] * Math.pow(10, max))
  }
  return count / Math.pow(10, max)
}

export function flatten(arr) {
  // 数组扁平化
  return arr.reduce((result, item) => {
    return result.concat(Array.isArray(item) ? flatten(item) : item)
  }, [])
}
export function handleMulitePerson(sPerson) {
  console.log(44, sPerson.split(','))
  if (typeof sPerson === 'string') {
    let personArr = []
    sPerson.split(',').forEach(item => {
      let obj = { userCode: item.split('/')[0], userName: item.split('/')[1] }
      personArr.push(obj)
    })
    return personArr
  }
}

export function uniqueArray(array, key) {
  // json数组根据key去重
  var result = [array[0]]
  for (var i = 1; i < array.length; i++) {
    var item = array[i]
    var repeat = false
    for (var j = 0; j < result.length; j++) {
      if (item[key] === result[j][key]) {
        repeat = true
        break
      }
    }
    if (!repeat) {
      result.push(item)
    }
  }
  return result
}

// export function urlParams() {
//   // 获取链接参数
//   var str = location.search.length > 0 ? location.search.substring(1) : "";
//   var items = str.length ? str.split("&") : [];
//   var args = {};
//   var item = null;
//   var name = null;
//   var value = null;
//   for (let i = 0, len = items.length; i < len; i++) {
//     item = items[i].split("=");
//     name = decodeURIComponent(item[0]);
//     value = decodeURIComponent(item[1]);
//     if (name.length) {
//       args[name] = value;
//     }
//   }
//   return args;
// }

export function urlAfterParams() {
  var str = window.location.hash.length > 0 ? window.location.hash.substring(window.location.hash.indexOf('?') + 1) : ''
  var items = str.indexOf('&') > 0 ? str.split('&') : str.split('?')
  var args = {}
  var item = null
  var name = null
  var value = null
  for (let i = 0, len = items.length; i < len; i++) {
    item = items[i].split('=')
    name = decodeURIComponent(item[0])
    value = decodeURIComponent(item[1])
    if (name.length) {
      args[name] = value
    }
  }
  return args
}
/**
 * @description echarts渲染通用
 * @param {String} id 容器id名
 * @param {Object} option 配置
 */
export function echartsFun(id, option) {
  // 基于准备好的dom，初始化echarts实例
  const myChart = echarts.init(document.getElementById(id))
  // 图表自适应
  setTimeout(function () {
    window.addEventListener('resize', function () {
      myChart.resize()
    })
  })
  // 使用刚指定的配置项和数据显示图表。
  myChart.setOption(option)
}
/**
 * @desc 获得视口尺寸
 */
export function getViewportOffset() {
  if (window.innerWidth) {
    return {
      w: window.innerWidth,
      h: window.innerHeight
    }
  } else {
    // ie8及其以下
    if (document.compatMode === 'BackCompat') {
      // 怪异模式
      return {
        w: document.body.clientWidth,
        h: document.body.clientHeight
      }
    } else {
      // 标准模式
      return {
        w: document.documentElement.clientWidth,
        h: document.documentElement.clientHeight
      }
    }
  }
}

/**
 * @desc 快排
 */
export function sort(arr) {
  if (arr.length <= 1) {
    return arr
  }
  const pivot = arr.splice(0, 1)[0]
  const left = [],
    right = []

  arr.forEach((item, index) => {
    if (item < pivot) {
      left.push(item)
    } else {
      right.push(item)
    }
  })
  // return arrSort(left).concat(pivot,arrSort(right))
  return [...sort(left), pivot, ...sort(right)]
}
export function promiseAll(promises) {
  return new Promise(function (resolve, reject) {
    if (!Array.isArray(promises)) {
      throw new TypeError(`argument must be a array`)
    }
    var resolvedCounter = 0
    var promiseNum = promises.length
    var resolvedResult = []
    for (let i = 0; i < promiseNum; i++) {
      Promise.resolve(promises[i]).then(
        value => {
          resolvedCounter++
          resolvedResult[i] = value
          if (resolvedCounter == promiseNum) {
            return resolve(resolvedResult)
          }
        },
        error => {
          return reject(error)
        }
      )
    }
  })
}
// test
let p1 = new Promise(function (resolve, reject) {
  setTimeout(function () {
    resolve(1)
  }, 1000)
})
let p2 = new Promise(function (resolve, reject) {
  setTimeout(function () {
    resolve(2)
  }, 2000)
})
let p3 = new Promise(function (resolve, reject) {
  setTimeout(function () {
    resolve(3)
  }, 3000)
})
promiseAll([p3, p1, p2]).then(res => {
  console.log(res) // [3, 1, 2]
})

/**
 * 数组扁平化
 */
//普通flat

export function flat1(arr) {
  let res = []
  arr.forEach(item => {
    if (Array.isArray(item)) {
      res.push(...flat1(item))
    } else {
      res.push(item)
    }
  })
  return res
}

// 使用reduce
export function flat2(arr) {
  return arr.reduce((pre, cur) => {
    return pre.concat(Array.isArray(cur) ? flat2(cur) : cur)
  }, [])
}
// 添加层数
// export function flat3(arr,num){
//   return num > 0 ? arr.reduce((pre,cur)=>{
//       return pre.concat(Array.isArray(cur)? flat3(cur,num-1):cur)
//   })
// }
//求滚动条滚动距离
export function getScrollOffset() {
  if (window.pageXOffset) {
    return {
      x: window.pageXOffset,
      y: window.pageYOffset
    }
  } else {
    return {
      x: document.body.scrollLeft + document.documentElement.scrollLeft,
      y: document.body.scrollTop + document.documentElement.scrollTop
    }
  }
}
//返回浏览器视口尺寸
export function getViewport() {
  if (window.innerWidth) {
    return {
      w: window.innerWidth,
      h: window.innerHeight
    }
  } else {
    if (document.compatMode === 'BackCompat') {
      return {
        w: document.body.clientWidth,
        h: document.body.clientHeight
      }
    } else {
      return {
        w: document.documentElement.clientWidth,
        h: document.documentElement.clientHeight
      }
    }
  }
}
//获取元素样式(兼容)
export function getStyle(elem, prop) {
  if (window.getComputedStyle) {
    return window.getComputedStyle(elem, null)[prop]
  } else {
    return elem.currentStyle[prop]
  }
}

export function addEvent(elem, type, handle) {
  if (elem.addEventListener) {
    elem.addEventListener(type, handle, false)
  } else if (elem.attachEvent) {
    elem.attachEvent('on' + type, function () {
      handle.call(elem)
    })
  } else {
    elem['on' + type] = handle
  }
}
//删除事件
export function removeEvent(elem, type, handle) {
  if (typeof elem.removeEventListener !== 'undefined') {
    elem.removeEventListener(type, handle, false)
  } else if (typeof elem.detachEvent !== 'undefined') {
    elem.detachEvent('on' + type)
  }
}
//取消冒泡
export function stopBubble(event) {
  if (event.stopPropagation) {
    event.stopPropagation()
  } else {
    event.cancelBubble = true
  }
}
// 阻止默认事件函数
export function cancelHandler(event) {
  if (event.preventDefault) {
    event.preventDefault()
  } else {
    event.returnValue = false
  }
}
export function drag(elem) {
  var disX, disY
  addEvent(elem, 'mousedown', function (e) {
    var event = e || window.event
    disX = event.clientX - parseInt(getStyle(elem, 'left'))
    disY = event.clientY - parseInt(getStyle(elem, 'top'))
    addEvent(document, 'mousemove', mouseMove)
    addEvent(document, 'mouseup', mouseUp)
    stopBubble(event)
    cancelHandler(event)
  })
  function mouseMove(e) {
    var event = e || window.event
    elem.style.left = event.clientX - disX + 'px'
    elem.style.top = event.clientY - disY + 'px'
  }
  function mouseUp(e) {
    var event = e || window.event
    removeEvent(document, 'mousemove', mouseMove)
    removeEvent(document, 'mouseup', mouseUp)
  }
}
//异步加载
export function loadScript(url, callback) {
  var script = document.createElement('script')
  script.type = 'text/javascript'
  if (script.readyState) {
    script.onreadstatechange = function () {
      //IE
      if (script.readyState == 'complete' || script.readyStatereadyState == 'loaded') {
        callback()
      }
    }
  } else {
    script.onload = function () {
      callback()
    }
  }
  script.src = url
  document.head.appendChild(script)
}
loadScript('/*路径*/', function () {
  test()
})
export function animateChange(element, target) {
  //清理定时器
  clearInterval(element.timeId)
  element.timeId = setInterval(function () {
    //获取元素的当前位置
    var current = element.offsetLeft
    //移动的步数
    var step = (target - current) / 10
    step = step > 0 ? Math.ceil(step) : Math.floor(step)
    current += step
    element.style.left = current + 'px'
    if (current == target) {
      //清理定时器
      clearInterval(element.timeId)
    }
    //测试代码:
    console.log('目标位置:' + target + ',当前位置:' + current + ',每次移动步数:' + step)
  }, 20)
}
my$('btn2').onclick = function () {
  animateChange(my$('dv'), 800)
}
//根据文件路径获取扩展名
getKzName(str){//获取文件路径的扩展名
	var url = str
	var pos = url.lastIndexOf(".");
	if(pos == -1){
		pos = url.lastIndexOf("\\")
	}
	ar filename = url.substr(pos +1);
	eturn filename
},
getKzName("xxxxx.mp4") //mp4
 
//判断是否手机号码
export function isPhone(str) {
    const reg = /^[1][3,4,5,7,8,9][0-9]{9}$/
    if (!reg.test(str)) {
      return false;
    } else {
      return true;
    }
}
 
//根据key截取url传参
export const getQueryString = (name) => {
    let urlArr = window.location.href.split('?');
    let str = null
    if (urlArr.length == 1) {
        str = null
        return str
    } else {
        urlArr = urlArr[1]
        urlArr = urlArr.split('&')
        urlArr.forEach(v => {
            if (v.indexOf(name) != -1) {
                str = v.split('=')[1] != undefined ? v.split('=')[1] : null
            }
        })
        return str;
    }
}
 
//将url上的参数转为json对象
export const getUrlParams=(str="?")=>{
    let urlstr = location.href;
    console.log(str.split(str)[1])
    let obj = {};
    if(urlstr.split(str)[1]){
        let arr = urlstr.split(str)[1].split("&");   //先通过？分解得到？后面的所需字符串，再将其通过&分解开存放在数组里
        for (let i of arr) {
            obj[i.split("=")[0]] = i.split("=")[1];  //对数组每项用=分解开，=前为对象属性名，=后为属性值
        }
        console.log("obj",obj);
    }else{
        console.log("无");
    }
    return obj
}
 
//时间格式化
export const formatDate = (date, fmt) => {
    date = date || new Date();
    fmt = fmt || 'yyyy-MM-dd hh:mm:ss';
    if (Object.prototype.toString.call(date).slice(8, -1) !== 'Date') {
        date = new Date(date)
    }
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
    }
    for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
            let str = o[k] + ''
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : (("00" + o[k]).substr(("" + o[k]).length)))
        }
    }
    return fmt
}
formatDate("时间戳",'YYYY-MM-dd HH:dd:ss')
 
//防抖
export const antiShake= (fn, t) => {
    let delay = t || 1000
    let timer
    return function () {
        let args = arguments;
        if (timer) {
            clearTimeout(timer)
        }
        let callNow = !timer
        timer = setTimeout(() => {
            timer = null
        }, delay)
        if (callNow) fn.apply(this, args)
    }
}
eventName:antiShake(function(){
    //do thing
})
// 金额格式化，20000->20.000,00强制保留2位小数，每隔三位用.隔开
export function moneyFormatWithDecimal(num) {
  num = num.toString()
  var num1 = parseFloat(num)
  if (isNaN(num1)) {
    return false
  }
  if (num.indexOf('.') >= 0) {
    var lastIndex = num.lastIndexOf('.')
    var num9 =
      num.substring(0, lastIndex) +
      ',' +
      num.substring(lastIndex + 1, num.length)
    const RegExp = /\B(?=(?:\d{3})+(?!\d))/g
    let numformat = num9 && num9.toString().replace(RegExp, '.')
    return numformat
  } else {
    var num2 = Math.round(num * 100) / 100
    var num3 = num2.toString()
    var num4 = num3.indexOf(',')
    if (num4 < 0) {
      num4 = num3.length
      num3 += ','
    }
    while (num3.length <= num4 + 2) {
      num3 += '0'
    }
    const RegExp = /\B(?=(?:\d{3})+(?!\d))/g
    let numformat = num3 && num3.toString().replace(RegExp, '.')
    return numformat
  }
}
export function formatDate(t, str) {
    var obj = {
        yyyy: t.getFullYear(),
        yy: ("" + t.getFullYear()).slice(-2),
        M: t.getMonth() + 1,
        MM: ("0" + (t.getMonth() + 1)).slice(-2),
        d: t.getDate(),
        dd: ("0" + t.getDate()).slice(-2),
        H: t.getHours(),
        HH: ("0" + t.getHours()).slice(-2),
        h: t.getHours() % 12,
        hh: ("0" + t.getHours() % 12).slice(-2),
        m: t.getMinutes(),
        mm: ("0" + t.getMinutes()).slice(-2),
        s: t.getSeconds(),
        ss: ("0" + t.getSeconds()).slice(-2),
        w: ['日', '一', '二', '三', '四', '五', '六'][t.getDay()]
    };
    return str.replace(/([a-z]+)/ig, function ($1) {
        return obj[$1]
    });
}
export function quickArr(arr) {
  if (arr.length <= 1) {
      return arr;
  }
  var left = [],
      right = [];
  var pIndex = Math.floor(arr.length / 2);
  var p = arr.splice(pIndex, 1)[0];
  for (var i = 0; i < arr.length; i++) {
      if (arr[i] <= p) {
          left.push(arr[i]);
      } else {
          right.push(arr[i]);
      }
  }
  // 递归
  return quickArr(left).concat([p], quickArr(right));
}

// 冒泡
export function bubbleSort(arr) {
  for (var i = 0; i < arr.length - 1; i++) {
      for (var j = i + 1; j < arr.length; j++) {
          if (arr[i] > arr[j]) {
              var temp = arr[i];
              arr[i] = arr[j];
              arr[j] = temp;
          }
      }
  }
  return arr;
}

export function bubbleSort(arr) {
  var len = arr.length;
  for (var i = 0; i < len - 1; i++) {
      for (var j = 0; j < len - 1 - i; j++) {
          if (arr[j] > arr[j + 1]) {
              var temp = arr[j];
              arr[j] = arr[j + 1];
              arr[j + 1] = temp;
          }
      }
  }
  return arr;
}
